package com.byhg.testcolor

import android.content.res.Resources
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.blur
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.LinearGradientShader
import androidx.compose.ui.graphics.ShaderBrush
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.TileMode
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.core.view.WindowCompat
import com.byhg.testcolor.MainActivity.ColorItem
import com.byhg.testcolor.ui.theme.TestcolorTheme
import org.burnoutcrew.reorderable.ReorderableItem
import org.burnoutcrew.reorderable.detectReorder
import org.burnoutcrew.reorderable.rememberReorderableLazyGridState
import org.burnoutcrew.reorderable.reorderable

class MainActivity : ComponentActivity() {
    data class ColorItem(val index: Int, val color: Color, val x: Float, val y: Float)

    data class ResultItem(
        val progress: Float,
        val angle: Float,
        val majorAngle: Float,
        val majore: Float,
        val minor: Float,
        val test: Float,
        val sIndex: Float,
        val cIndex: Float
    )

    data class AngleItem(val x: Float, val y: Float)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            TestcolorTheme {
                WindowCompat.setDecorFitsSystemWindows(window, false)
                val colors = remember {
                    mutableListOf<ColorItem>(
                        ColorItem(0, Color(55, 129, 193), -38.39f, -21.54f),
                        ColorItem(1, Color(53, 131, 180), -25.56f, -23.26f),
                        ColorItem(2, Color(59, 132, 167), -15.53f, -22.41f),
                        ColorItem(3, Color(57, 133, 156), -7.45f, -23.11f),
                        ColorItem(4, Color(59, 134, 144), 1.1f, -22.45f),
                        ColorItem(5, Color(63, 135, 130), 7.35f, -21.76f),
                        ColorItem(6, Color(88, 132, 115), 18.74f, -14.08f),
                        ColorItem(7, Color(108, 129, 100), 28.13f, -2.72f),
                        ColorItem(8, Color(131, 123, 93), 31.13f, 14.84f),
                        ColorItem(9, Color(144, 118, 96), 26.35f, 23.87f),
                        ColorItem(10, Color(158, 110, 111), 14.76f, 31.82f),
                        ColorItem(11, Color(159, 109, 124), 6.99f, 31.42f),
                        ColorItem(12, Color(156, 109, 137), 0.1f, 29.79f),
                        ColorItem(13, Color(146, 112, 153), -9.33f, 26.64f),
                        ColorItem(14, Color(143, 111, 164), -18.65f, 22.92f),
                        ColorItem(15, Color(128, 115, 178), -24.61f, 11.2f),
                    )
                }
                colors.shuffle()
                if (resources.configuration.orientation == 2) {
                    HorizontalReorderGrid(colors)
                } else {
                    VerticalReorderGrid(colors)
                }
            }

        }
    }
}

// 扩展函数来格式化浮点数到小数点后一位
fun Float.formatToOneDecimalPlace(): String {
    return "%.1f".format(this)
}

fun Float.formatToTwoDecimalPlace(): String {
    return "%.2f".format(this)
}

private fun calculateMoments(rowData: List<ColorItem>): MainActivity.ResultItem {

    val angleList = arrayListOf<MainActivity.AngleItem>()
    for (i in rowData.indices) {
        if (i == 0) continue
        angleList.add(
            MainActivity.AngleItem(
                rowData[i - 1].x - rowData[i].x, rowData[i - 1].y - rowData[i].y
            )
        )
    }


    var sum1 = 0f
    var sum2 = 0f
    for (i in angleList.indices) {
        val colorItem = angleList[i]
        sum1 += 2 * colorItem.x * colorItem.y
        sum2 += Math.pow(colorItem.y.toDouble(), 2.0).toFloat() - Math.pow(
            colorItem.x.toDouble(), 2.0
        ).toFloat()
    }
    val angle1 = Math.atan(sum1.toDouble() / sum2.toDouble()).toFloat() / 2f

    val angle2 =
        if (angle1 < 0) angle1 + (Math.PI.toFloat() / 2f) else angle1 - (Math.PI.toFloat() / 2f)

    var moms1 = 0f
    var moms2 = 0f
    for (i in angleList.indices) {
        moms1 += Math.pow(
            angleList[i].x.toDouble() * Math.cos(angle1.toDouble()) - angleList[i].y.toDouble() * Math.sin(
                angle1.toDouble()
            ), 2.0
        ).toFloat()
        moms2 += Math.pow(
            angleList[i].x.toDouble() * Math.cos(angle2.toDouble()) - angleList[i].y.toDouble() * Math.sin(
                angle2.toDouble()
            ), 2.0
        ).toFloat()
    }
    moms1 = Math.sqrt(moms1.toDouble() / angleList.size.toDouble()).toFloat()
    moms2 = Math.sqrt(moms2.toDouble() / angleList.size.toDouble()).toFloat()

    var test = 0f
    var cIndex = 0f
    var sIndex = 0f
    var majorAngle = 0f
    if (moms1 > moms2) {
        cIndex = moms1 / 9.23705f
        sIndex = moms1 / moms2
        majorAngle = (180f * angle2 / Math.PI).toFloat()
        test =
            Math.sqrt(Math.pow(moms1.toDouble(), 2.0) + Math.pow(moms2.toDouble(), 2.0)).toFloat()
    } else {
        cIndex = moms2 / 9.23705f
        sIndex = moms2 / moms1
        majorAngle = (180f * angle1 / Math.PI).toFloat()
        test =
            Math.sqrt(Math.pow(moms2.toDouble(), 2.0) + Math.pow(moms1.toDouble(), 2.0)).toFloat()
    }


    val progress: Float = (cIndex - 1.6f) / (4.2f - 1.6f)
    return MainActivity.ResultItem(progress, angle1, majorAngle, moms1, moms2, test, sIndex, cIndex)
}

/**
 *
 * 全屏的 dialog 显示
 *
 */
@Composable
private fun FullScreenDialog(
    showDialog: Boolean,
    rowData: List<ColorItem>,
    score: Float,
    correct: Int,
    partial: Int,
    wrong: Int,
    onParentDismiss: () -> Unit
) {

    val calculateMoments = calculateMoments(rowData)
    var resultMark = ""
    if (calculateMoments.cIndex <= 1.6f) {
        resultMark = "not colorblind"
    } else if (calculateMoments.majorAngle >= 0.7f) {
        resultMark = "protan color vision defect"
    } else if (calculateMoments.majorAngle < -65f) {
        resultMark = "tritan color vision defect"
    } else {
        resultMark = "deutan color vision defect"
    }
    val textMeasurer = rememberTextMeasurer()
    val origin = rowData.sortedBy { it.index }
    val originMaxX = 45
    val originMaxY = 45
    if (showDialog) {
        Dialog(
            onDismissRequest = onParentDismiss,

            properties = DialogProperties(
                usePlatformDefaultWidth = false,
                dismissOnClickOutside = true,
                decorFitsSystemWindows = false,
            ),
        ) {
            Surface(
                color = Color.White,
                modifier = Modifier
                    .width(630.dp)
                    .height(310.dp)
                    .offset(-12.dp,-12.dp)
                    .shadow(2.dp, RoundedCornerShape(32.dp))
            ) {
                Row(
                    modifier = Modifier.fillMaxSize()
                ) {
                    Spacer(modifier = Modifier.size(20.dp))
                    Canvas(modifier = Modifier.aspectRatio(1f, true), onDraw = {
                        val w = size.width
                        val h = size.height
                        val lineW = 2f

                        // 卡迪尔X轴
                        drawLine(
                            start = Offset(0f, h * 1f / 2f - lineW / 2f),
                            end = Offset(w, h * 1f / 2f - lineW / 2f),
                            color = Color.Transparent,
                            strokeWidth = lineW,
                            cap = StrokeCap.Square,
                            alpha = 1f
                        )


                        // 卡迪尔Y轴
                        drawLine(
                            start = Offset(w * 1f / 2f - lineW / 2f, 0f),
                            end = Offset(w * 1f / 2f - lineW / 2f, h),
                            color = Color.Transparent,
                            strokeWidth = lineW,
                            cap = StrokeCap.Square,
                            alpha = 1f
                        )


                        val pW = 6f
                        // protan
                        val protanSX = 1.74f / originMaxX * w * 0.5f + w * 0.5f - pW * 0.5f
                        val protanSY = 35f / originMaxY * h * 0.5f + h * 0.5f
                        val protanEX = -1.74f / originMaxX * w * 0.5f + w * 0.5f - pW * 0.5f
                        val protanEY = -35f / originMaxY * h * 0.5f + h * 0.5f
                        drawLine(
                            start = Offset(protanSX, protanSY),
                            end = Offset(protanEX, protanEY),
                            color = Color.Red,
                            strokeWidth = pW,
                            cap = StrokeCap.Square,
                            alpha = 1f
                        )
                        val protanTextMeasurer = textMeasurer.measure(
                            text = "protan", style = TextStyle(
                                color = Color.Red,
                                textAlign = TextAlign.Center,
                                fontSize = 12.sp,
                            )
                        )
                        drawText(
                            protanTextMeasurer, topLeft = Offset(
                                protanEX - protanTextMeasurer.size.width * 0.8f,
                                protanEY - protanTextMeasurer.size.height * 1.3f
                            )
                        )

                        // deutan
                        val deutanSX = -7.77f / originMaxX * w * 0.5f + w * 0.5f - pW * 0.5f
                        val deutanSY = 35f / originMaxY * h * 0.5f + h * 0.5f
                        val deutanEX = 7.77f / originMaxX * w * 0.5f + w * 0.5f - pW * 0.5f
                        val deutanEY = -35f / originMaxY * h * 0.5f + h * 0.5f
                        drawLine(
                            start = Offset(deutanSX, deutanSY),
                            end = Offset(deutanEX, deutanEY),
                            color = Color.Green,
                            strokeWidth = pW,
                            cap = StrokeCap.Square,
                            alpha = 1f
                        )
                        val deutanTextMeasurer = textMeasurer.measure(
                            text = "deutan", style = TextStyle(
                                color = Color.Green,
                                textAlign = TextAlign.Center,
                                fontSize = 12.sp,
                            )
                        )
                        drawText(
                            deutanTextMeasurer, topLeft = Offset(
                                deutanEX - deutanTextMeasurer.size.width * 0.2f,
                                deutanEY - deutanTextMeasurer.size.height * 1.3f
                            )
                        )


                        // tritan
                        val tritanSX = -35f / originMaxX * w * 0.5f + w * 0.5f - pW * 0.5f
                        val tritanSY = 4.92f / originMaxY * h * 0.5f + h * 0.5f
                        val tritanEX = 35f / originMaxX * w * 0.5f + w * 0.5f - pW * 0.5f
                        val tritanEY = -4.92f / originMaxY * h * 0.5f + h * 0.5f
                        drawLine(
                            start = Offset(tritanSX, tritanSY),
                            end = Offset(tritanEX, tritanEY),
                            color = Color.Blue,
                            strokeWidth = pW,
                            cap = StrokeCap.Square,
                            alpha = 1f
                        )
                        val tritanTextMeasurer = textMeasurer.measure(
                            text = "tritan", style = TextStyle(
                                color = Color.Blue,
                                textAlign = TextAlign.Center,
                                fontSize = 12.sp,
                            )
                        )
                        drawText(
                            tritanTextMeasurer, topLeft = Offset(
                                tritanSX - tritanTextMeasurer.size.width,
                                tritanSY + tritanTextMeasurer.size.height * 0.2f
                            )
                        )

                        val orderPoint = arrayListOf<Pair<Int, Offset>>();
                        for (i in origin.indices) {
                            val colorItem = origin[i]
                            val recSize = 30f
                            val kdrWF = (w) * 0.5f
                            val kdrHF = (h) * 0.5f
                            val recX = colorItem.x / originMaxX * kdrWF + kdrWF
                            val recY = colorItem.y / originMaxY * kdrHF + kdrHF
                            drawRoundRect(
                                color = colorItem.color,
                                topLeft = Offset(recX, recY),
                                size = Size(recSize, recSize),
                                cornerRadius = CornerRadius.Zero
                            )
                            //在上面那个矩形上绘制文字
                            val text = if (colorItem.index == 0) "P" else "${colorItem.index}"
                            val textLayoutResult = textMeasurer.measure(
                                text = text, style = TextStyle(
                                    color = Color.Black,
                                    textAlign = TextAlign.Center,
                                    fontSize = 12.sp,
                                )
                            )
                            val textX = recX + recSize * 0.5f - textLayoutResult.size.width * 0.5f
                            val tempY = recY + recSize * 0.5f
                            val textY =
                                tempY + if (tempY > (h) * 1f / 2f) textLayoutResult.size.height * 0.3f else -textLayoutResult.size.height * 1f - textLayoutResult.size.height * 0.3f
                            drawText(
                                textLayoutResult, topLeft = Offset(textX, textY)
                            )
                            orderPoint.add(
                                Pair(
                                    colorItem.index,
                                    Offset(recX + recSize * 0.5f, recY + recSize * 0.5f)
                                )
                            )
                        }
                        //绘制线段箭头
                        for (i in 0 until rowData.size - 1) {
                            val indexStart = rowData[i].index
                            val indexEnd = rowData[i + 1].index
                            val colorStart = rowData[i].color
                            val colorEnd = rowData[i + 1].color
                            val p1 = orderPoint[indexStart]
                            val p2 = orderPoint[indexEnd]

                            // 创建线性渐变
                            val brush = ShaderBrush(
                                LinearGradientShader(
                                    colors = listOf(colorStart, colorStart),
                                    from = p1.second,
                                    to = p2.second,
                                    tileMode = TileMode.Clamp
                                )
                            )


                            drawLine(
                                start = p1.second,
                                end = p2.second,
                                brush = brush,
                                strokeWidth = 2f,
                                cap = StrokeCap.Square,
                                alpha = 1f
                            )

                            //实现上面那个方法
                            val arrowLength = 20f
                            val arrowWidth = 10f
                            val arrowHeight = 10f
                            //箭头顶点是p2.second
                            val arrowDirection =
                                (p2.second.x - p1.second.x) / (p2.second.y - p1.second.y)
                            val arrowX = p2.second.x
                            val arrowY = p2.second.y
                            val arrowX2 = p2.second.x - arrowLength * arrowDirection
                            val arrowY2 = p2.second.y + arrowLength * arrowHeight / arrowWidth
                            val arrowX3 = p2.second.x + arrowLength * arrowDirection
                            val arrowY3 = p2.second.y + arrowLength * arrowHeight / arrowWidth
                            //三点确定一个三角形箭头
                        }

                    })
                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(end = 20.dp)
                            .background(Color.White)


                    ) {
                        Column(modifier = Modifier.fillMaxSize()) {

                            Spacer(
                                Modifier
                                    .height(20.dp)
                                    .fillMaxWidth()
                            )
                            Text(
                                "D-15 Disc Arrangement CVD Test",
                                modifier = Modifier.align(Alignment.CenterHorizontally),
                                style = TextStyle(fontSize = 15.sp)
                            )

                            Spacer(
                                Modifier
                                    .height(20.dp)
                                    .fillMaxWidth()
                            )
                            val rowHeight = 100.dp
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .border(1.dp, Color(135, 206, 250))
                                    .padding(1.dp)
                            ) {
                                Box(
                                    modifier = Modifier
                                        .weight(1f)
                                        .height(rowHeight)
                                ) {
                                    Column(modifier = Modifier.fillMaxSize()) {
                                        Box(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .weight(1f)
                                                .background(Color(240, 248, 255))
                                        ) {
                                            Text(
                                                "ANGLE",
                                                modifier = Modifier.align(Alignment.Center),
                                                style = TextStyle(
                                                    fontSize = 12.sp,
                                                    color = Color.Black,
                                                    fontWeight = FontWeight.Bold
                                                )
                                            )
                                        }
                                        Spacer(
                                            Modifier
                                                .fillMaxWidth()
                                                .height(1.dp)
                                                .background(Color(135, 206, 250))
                                        )
                                        Box(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .weight(1f)
                                                .background(Color.Transparent)
                                        ) {
                                            Text(
                                                calculateMoments.majorAngle.formatToOneDecimalPlace(),
                                                modifier = Modifier.align(Alignment.Center),
                                                style = TextStyle(
                                                    fontSize = 12.sp,
                                                    color = Color.Black,
                                                    fontWeight = FontWeight.Normal
                                                )
                                            )
                                        }
                                        Spacer(
                                            Modifier
                                                .fillMaxWidth()
                                                .height(1.dp)
                                                .background(Color(135, 206, 250))
                                        )
                                        Box(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .weight(1f)
                                                .background(Color(240, 248, 255))
                                        ) {
                                            Text(
                                                "TEST",
                                                modifier = Modifier.align(Alignment.Center),
                                                style = TextStyle(
                                                    fontSize = 12.sp,
                                                    color = Color.Black,
                                                    fontWeight = FontWeight.Bold
                                                )
                                            )
                                        }
                                        Spacer(
                                            Modifier
                                                .fillMaxWidth()
                                                .height(1.dp)
                                                .background(Color(135, 206, 250))
                                        )
                                        Box(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .weight(1f)
                                                .background(Color.Transparent)
                                        ) {
                                            Text(
                                                calculateMoments.test.formatToOneDecimalPlace(),
                                                modifier = Modifier.align(Alignment.Center),
                                                style = TextStyle(
                                                    fontSize = 12.sp,
                                                    color = Color.Black,
                                                    fontWeight = FontWeight.Normal
                                                )
                                            )
                                        }
                                    }
                                }

                                Spacer(
                                    Modifier
                                        .width(1.dp)
                                        .height(rowHeight)
                                        .background(Color(135, 206, 250))
                                )
                                Box(
                                    modifier = Modifier
                                        .weight(1f)
                                        .height(rowHeight)
                                ) {
                                    Column(modifier = Modifier.fillMaxSize()) {
                                        Box(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .weight(1f)
                                                .background(Color(240, 248, 255))
                                        ) {
                                            Text(
                                                "MAJOR",
                                                modifier = Modifier.align(Alignment.Center),
                                                style = TextStyle(
                                                    fontSize = 12.sp,
                                                    color = Color.Black,
                                                    fontWeight = FontWeight.Bold
                                                )
                                            )
                                        }
                                        Spacer(
                                            Modifier
                                                .fillMaxWidth()
                                                .height(1.dp)
                                                .background(Color(135, 206, 250))
                                        )
                                        Box(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .weight(1f)
                                                .background(Color.Transparent)
                                        ) {
                                            Text(
                                                calculateMoments.majore.formatToOneDecimalPlace(),
                                                modifier = Modifier.align(Alignment.Center),
                                                style = TextStyle(
                                                    fontSize = 12.sp,
                                                    color = Color.Black,
                                                    fontWeight = FontWeight.Normal
                                                )
                                            )
                                        }
                                        Spacer(
                                            Modifier
                                                .fillMaxWidth()
                                                .height(1.dp)
                                                .background(Color(135, 206, 250))
                                        )
                                        Box(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .weight(1f)
                                                .background(Color(240, 248, 255))
                                        ) {
                                            Text(
                                                "S-INDEX",
                                                modifier = Modifier.align(Alignment.Center),
                                                style = TextStyle(
                                                    fontSize = 12.sp,
                                                    color = Color.Black,
                                                    fontWeight = FontWeight.Bold
                                                )
                                            )
                                        }
                                        Spacer(
                                            Modifier
                                                .fillMaxWidth()
                                                .height(1.dp)
                                                .background(Color(135, 206, 250))
                                        )
                                        Box(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .weight(1f)
                                                .background(Color.Transparent)
                                        ) {
                                            Text(
                                                calculateMoments.sIndex.formatToTwoDecimalPlace(),
                                                modifier = Modifier.align(Alignment.Center),
                                                style = TextStyle(
                                                    fontSize = 12.sp,
                                                    color = Color.Black,
                                                    fontWeight = FontWeight.Normal
                                                )
                                            )
                                        }
                                    }
                                }

                                Spacer(
                                    Modifier
                                        .width(1.dp)
                                        .height(rowHeight)
                                        .background(Color(135, 206, 250))
                                )
                                Box(
                                    modifier = Modifier
                                        .weight(1f)
                                        .height(rowHeight)
                                ) {
                                    Column(modifier = Modifier.fillMaxSize()) {
                                        Box(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .weight(1f)
                                                .background(Color(240, 248, 255))
                                        ) {
                                            Text(
                                                "MINOR",
                                                modifier = Modifier.align(Alignment.Center),
                                                style = TextStyle(
                                                    fontSize = 12.sp,
                                                    color = Color.Black,
                                                    fontWeight = FontWeight.Bold
                                                )
                                            )
                                        }
                                        Spacer(
                                            Modifier
                                                .fillMaxWidth()
                                                .height(1.dp)
                                                .background(Color(135, 206, 250))
                                        )
                                        Box(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .weight(1f)
                                                .background(Color.Transparent)
                                        ) {
                                            Text(
                                                calculateMoments.minor.formatToOneDecimalPlace(),
                                                modifier = Modifier.align(Alignment.Center),
                                                style = TextStyle(
                                                    fontSize = 12.sp,
                                                    color = Color.Black,
                                                    fontWeight = FontWeight.Normal
                                                )
                                            )
                                        }
                                        Spacer(
                                            Modifier
                                                .fillMaxWidth()
                                                .height(1.dp)
                                                .background(Color(135, 206, 250))
                                        )
                                        Box(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .weight(1f)
                                                .background(Color(240, 248, 255))
                                        ) {
                                            Text(
                                                "C-INDEX",
                                                modifier = Modifier.align(Alignment.Center),
                                                style = TextStyle(
                                                    fontSize = 12.sp,
                                                    color = Color.Black,
                                                    fontWeight = FontWeight.Bold
                                                )
                                            )
                                        }
                                        Spacer(
                                            Modifier
                                                .fillMaxWidth()
                                                .height(1.dp)
                                                .background(Color(135, 206, 250))
                                        )
                                        Box(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .weight(1f)
                                                .background(Color.Transparent)
                                        ) {
                                            Text(
                                                calculateMoments.cIndex.formatToTwoDecimalPlace(),
                                                modifier = Modifier.align(Alignment.Center),
                                                style = TextStyle(
                                                    fontSize = 12.sp,
                                                    color = Color.Black,
                                                    fontWeight = FontWeight.Normal
                                                )
                                            )
                                        }
                                    }
                                }
                            }
                            Spacer(
                                Modifier
                                    .height(20.dp)
                                    .fillMaxWidth()
                            )
                            Text(
                                "According to this test result you have a",
                                modifier = Modifier.align(Alignment.Start),
                                style = TextStyle(
                                    fontSize = 14.sp,
                                    color = Color.Black,
                                    fontWeight = FontWeight.Normal
                                )
                            )
                            Spacer(
                                Modifier
                                    .height(6.dp)
                                    .fillMaxWidth()
                            )
                            Text(
                                resultMark,
                                modifier = Modifier.align(Alignment.CenterHorizontally),
                                style = TextStyle(
                                    fontSize = 20.sp,
                                    color = Color.Red,
                                    fontWeight = FontWeight.Normal
                                )
                            )
                            Spacer(
                                Modifier
                                    .height(6.dp)
                                    .fillMaxWidth()
                            )
                            var containerSize by remember { mutableStateOf(IntSize.Zero) }
                            Box(modifier = Modifier
                                .fillMaxWidth()
                                .onGloballyPositioned { containerSize = it.size }
                                .height(30.dp)
                                .padding(2.dp)
                                .border(2.dp, Color(170, 170, 170))) {
                                Box(
                                    modifier = Modifier
                                        .fillMaxHeight()
                                        .width((containerSize.width.toFloat() * calculateMoments.progress).pxToDp())
                                        .background(Color(135, 205, 250))
                                )
                                Text(
                                    "severity",
                                    modifier = Modifier.align(Alignment.Center),
                                    style = TextStyle(
                                        fontSize = 14.sp,
                                        color = Color.Black,
                                        fontWeight = FontWeight.SemiBold
                                    )
                                )
                            }
                            Row(modifier = Modifier.fillMaxWidth()) {
                                Text(
                                    "slightly",
                                    modifier = Modifier.weight(1f),
                                    textAlign = TextAlign.Center,
                                    style = TextStyle(
                                        fontSize = 10.sp, color = Color.Black
                                    )
                                )
                                Text(
                                    "moderate",
                                    modifier = Modifier.weight(1f),
                                    textAlign = TextAlign.Center,
                                    style = TextStyle(
                                        fontSize = 10.sp, color = Color.Black
                                    )
                                )
                                Text(
                                    "strong",
                                    modifier = Modifier.weight(1f),
                                    textAlign = TextAlign.Center,
                                    style = TextStyle(
                                        fontSize = 10.sp, color = Color.Black
                                    )
                                )
                            }

                        }
                    }
                }
            }

        }
    }
}

fun Float.pxToDp(): Dp {
    val density = Resources.getSystem().displayMetrics.density
    return Dp(this / density + 0.5f)
}

@Composable
fun VerticalReorderGrid(colors: MutableList<ColorItem>) {
    val data = remember {
        mutableStateOf(List(colors.size) {
            colors[it]
        })
    }
    val (openDialog, setOpenDialog) = remember { mutableStateOf(false) }
    val state = rememberReorderableLazyGridState(onMove = { from, to ->
        data.value = data.value.toMutableList().apply {
            add(to.index, removeAt(from.index))
        }
    })
    var score by remember { mutableFloatStateOf(0f) }
    var correct by remember { mutableIntStateOf(0) }
    var partial by remember { mutableIntStateOf(0) }
    var wrong by remember { mutableIntStateOf(0) }
    Box(
        modifier = Modifier
            .fillMaxSize()
            .padding(horizontal = 16.dp)
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(80.dp)
                .offset(0.dp, 80.dp)
        ) {
            Text(
                text = "Color Arrangement Test",
                modifier = Modifier.align(Alignment.Center),
                fontSize = 30.sp
            )
        }
        Box(modifier = Modifier.fillMaxSize()) {
            LazyVerticalGrid(
                columns = GridCells.Fixed(4),
                state = state.gridState,
                modifier = Modifier
                    .reorderable(state)
                    .align(Alignment.Center)
            ) {
                items(data.value, key = { it.index }) { item ->
                    ReorderableItem(
                        state,
                        key = item.index,
                        defaultDraggingModifier = Modifier,
                        orientationLocked = false
                    ) { isDragging ->
                        val elevation =
                            animateDpAsState(if (isDragging) 16.dp else 0.dp, label = "")
                        Box(
                            modifier = Modifier
                                .padding(1.dp)
                                .aspectRatio(1f, false)
                        ) {
                            Box(
                                modifier = Modifier
                                    .fillMaxSize()
                                    .detectReorder(state)
                                    .shadow(elevation.value)
                                    .background(item.color)
                            )
                        }
                    }
                }
            }
        }

        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(50.dp)
                .align(Alignment.BottomCenter)
                .offset(0.dp, (-100).dp)
        ) {
            Button(
                onClick = {
                    correct = 0
                    partial = 0
                    wrong = 0
                    data.value.forEachIndexed { index, pair ->
                        when (index) {
                            pair.index -> {
                                correct++
                            }

                            pair.index + 1, pair.index - 1 -> {
                                partial++
                            }

                            else -> {
                                wrong++
                            }
                        }
                    }
                    score = (correct * 1f / data.value.size) * 100f
                    setOpenDialog(true)
                },
                modifier = Modifier
                    .align(Alignment.Center)
                    .height(50.dp)
                    .width(160.dp),
                shape = RoundedCornerShape(16.dp), // Set rounded corner shape
            ) {
                Text(text = "Ok", fontSize = 20.sp)
            }
        }


        FullScreenDialog(showDialog = openDialog,
            data.value,
            score,
            correct,
            partial,
            wrong,
            onParentDismiss = {
                data.value = data.value.shuffled()
                setOpenDialog(false)
            })
    }
}

@Composable
fun HorizontalReorderGrid(colors: MutableList<ColorItem>) {
    val data = remember {
        mutableStateOf(List(colors.size) {
            colors[it]
        })
    }
    val (openDialog, setOpenDialog) = remember { mutableStateOf(false) }
    val state = rememberReorderableLazyGridState(onMove = { from, to ->
        data.value = data.value.toMutableList().apply {
            add(to.index, removeAt(from.index))
        }
    })
    var score by remember { mutableFloatStateOf(0f) }
    var correct by remember { mutableIntStateOf(0) }
    var partial by remember { mutableIntStateOf(0) }
    var wrong by remember { mutableIntStateOf(0) }
    Box(
        modifier = Modifier
            .fillMaxSize()
            .padding(horizontal = 50.dp)
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(80.dp)
                .offset(0.dp, 30.dp)
        ) {
            Text(
                text = "Color Arrangement Test",
                modifier = Modifier.align(Alignment.Center),
                fontSize = 30.sp
            )
        }
        Box(modifier = Modifier.align(Alignment.Center)) {
            LazyVerticalGrid(
                columns = GridCells.Fixed(16),
                state = state.gridState,
                modifier = Modifier
                    .reorderable(state)
                    .align(Alignment.TopStart)
            ) {
                items(data.value, key = { it.index }) { item ->
                    ReorderableItem(
                        state,
                        key = item.index,
                        defaultDraggingModifier = Modifier,
                        orientationLocked = false
                    ) { isDragging ->
                        val elevation =
                            animateDpAsState(if (isDragging) 16.dp else 0.dp, label = "")
                        Box(
                            modifier = Modifier
                                .padding(1.dp)
                                .aspectRatio(0.5f, false)
                        ) {
                            Box(
                                modifier = Modifier
                                    .fillMaxSize()
                                    .detectReorder(state)
                                    .shadow(elevation.value)
                                    .background(item.color)
                            )
                        }

                    }


                }
            }
        }

        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(50.dp)
                .align(Alignment.BottomCenter)
                .offset(0.dp, (-40).dp)
        ) {
            Button(
                onClick = {
                    correct = 0
                    partial = 0
                    wrong = 0
                    data.value.forEachIndexed { index, pair ->
                        when (index) {
                            pair.index -> {
                                correct++
                            }

                            pair.index + 1, pair.index - 1 -> {
                                partial++
                            }

                            else -> {
                                wrong++
                            }
                        }
                    }
                    score = (correct * 1f / data.value.size) * 100f
                    setOpenDialog(true)
                },
                modifier = Modifier
                    .align(Alignment.Center)
                    .height(50.dp)
                    .width(160.dp),
                shape = RoundedCornerShape(16.dp), // Set rounded corner shape
            ) {
                Text(text = "Ok", fontSize = 20.sp)
            }
        }

        FullScreenDialog(showDialog = openDialog,
            data.value,
            score,
            correct,
            partial,
            wrong,
            onParentDismiss = {
                data.value = data.value.shuffled()
                setOpenDialog(false)
            })
    }
}

@Composable
fun AlertDialogSample(
    showDialog: Boolean,
    rowData: List<ColorItem>,
    score: Float,
    correct: Int,
    partial: Int,
    wrong: Int,
    onParentDismiss: () -> Unit
) {
    if (showDialog) {
        AlertDialog(onDismissRequest = onParentDismiss, title = {
            Text(text = "YOUR SCORE $score")
        }, text = {
            Text("Correct:$correct\r\nPartial:$partial\r\nWrong:$wrong")
        }, confirmButton = {
            TextButton(onClick = onParentDismiss) {
                Text("确认")
            }
        })
    }
}
